package com.ibl.rover.lite.client.Activity;

import java.util.ArrayList;
import java.util.List;
import com.ibl.rover.lite.client.Logger;
import com.ibl.rover.lite.client.R;
import com.ibl.rover.lite.client.Application.ApplicationContext;
import com.ibl.rover.lite.client.Application.OrderBookingLine;
import com.ibl.rover.lite.client.constants.RoverConstants;
import com.ibl.rover.lite.common.bean.ProductBean;
import com.ibl.rover.lite.common.bean.ProductCategroy;
import com.ibl.rover.lite.common.db.Criteria;
import com.ibl.rover.lite.common.db.Criteria.Operators;
import com.ibl.rover.lite.common.db.DatabaseManager;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TableRow.LayoutParams;

public class SearchProductActivity extends Activity implements OnClickListener {

	private Logger logger = new Logger();
	private ApplicationContext roverApp;
	private DatabaseManager manager = null;
	private List<ProductBean> productBeans;
	private ProductCategroy productCategroy;
	private OrderBookingLine orderBookingLine;
	private ProgressDialog progressDlg = null;
	private Handler handler = new Handler();
	private EditText searchFilter;
	private boolean isSearching;
	Thread searchThread;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.search_product);

			initialize();
		} catch (Exception e) {
			logger.logException("onCreate Exceotion", e);
		}
	}

	/**
	 * Initialize Resources
	 */
	private void initialize() {
		try {
			searchThread = new Thread();
			roverApp = (ApplicationContext) getApplication();
			manager = roverApp.getDatabaseManager();
			isSearching = false;
			productCategroy = (ProductCategroy) roverApp.getViewContext().get(
					RoverConstants.CURRENT_SELECTED_SKU);
			orderBookingLine = (OrderBookingLine) roverApp.getViewContext()
					.get(RoverConstants.CURRENT_ORDER_BOOKING_LINE);

			if (orderBookingLine.getProductBeanList() == null) {
				orderBookingLine
						.setProductBeanList(new ArrayList<ProductBean>());
				orderBookingLine
						.setProductQuantitylist(new ArrayList<String>());
			}

			Criteria<ProductBean> criteria = manager
					.generateCriteria(ProductBean.class);
			if (productCategroy != null) {
				criteria.addRestriction(ProductBean.COL_PRODUCT_CATEGORY_ID,
						Operators.isEqual, productCategroy.getCategoryCode());
			}
			criteria.setOrderBy(ProductBean.COL_DESCRIPTION, true);
			productBeans = criteria.execute();

			progressDlg = new ProgressDialog(this);
			progressDlg.setMessage("Please Wait!");
			progressDlg.setTitle("Searching...");
			progressDlg.setCancelable(false);
			progressDlg.show();

			Thread thread = new Thread() {
				public void run() {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					handler.post(new Runnable() {
						@Override
						public void run() {

							buildProductTable();
							progressDlg.dismiss();
						}
					});

				}
			};
			thread.start();

			 ((ImageButton) findViewById(R.id.search_product))
			 .setOnClickListener(this);
			 ((Button) findViewById(R.id.clear_product))
			 .setOnClickListener(this);
			// ((Button) findViewById(R.id.cancel_result))
			// .setOnClickListener(this);
			searchFilter = (EditText) findViewById(R.id.id_search_val);
			// searchFilter.setOnKeyListener(new OnKeyListener() {
			//
			// @Override
			// public boolean onKey(View v, int keyCode, KeyEvent event) {
			//
			// filterproducts();
			// return false;
			// }
			// });

//			searchFilter.addTextChangedListener(new TextWatcher() {
//
//				@Override
//				public void onTextChanged(CharSequence arg0, int arg1,
//						int arg2, int arg3) {
//					// TODO Auto-generated method stub
//
//				}
//
//				@Override
//				public void beforeTextChanged(CharSequence arg0, int arg1,
//						int arg2, int arg3) {
//					// TODO Auto-generated method stub
//
//				}
//
//				@Override
//				public void afterTextChanged(Editable arg0) {
//					filterproducts();
//
//				}
//			});

		} catch (Exception e) {
			logger.logException("Initializer Exception :", e);
		}

	}

	public void delay() {
		searchThread = new Thread() {

			public void run() {
				try {
					Thread.sleep(2500);
					SearchProductActivity.this.filterproducts();
				} catch (InterruptedException ex) {
					// ex.printStackTrace();
				}
			}
		};
		searchThread.start();

	}

	public void filterproducts() {
		try {
//			roverApp.showMessage("Search Start ", Toast.LENGTH_SHORT);
			String filterValue = searchFilter.getText().toString()
					.toLowerCase().trim();
			isSearching = true;
			TableLayout productsTable = (TableLayout) findViewById(R.id.search_result_dlg);
			int count = productsTable.getChildCount();
			TableRow row;
			String productCode;
			for (int i = 1; i < count; i++) {
				row = (TableRow) productsTable.getChildAt(i);
				productCode = "";
				productCode = ((TextView) row.getChildAt(0)).getText()
						.toString();

				if (!productCode.toLowerCase().contains(filterValue)
						&& !filterValue.equals(""))
					row.setVisibility(TableRow.GONE);
				else
					row.setVisibility(TableRow.VISIBLE);
			}

			productsTable.refreshDrawableState();
			productsTable.invalidate();

		} catch (Exception e) {
			logger.logException("filterproduction Exception", e);
		} finally {
			isSearching = false;
		}
	}

	
	public void filterClearProducts() {
		try {
//			roverApp.showMessage("Search Start ", Toast.LENGTH_SHORT);
//			String filterValue = searchFilter.getText().toString()
//					.toLowerCase().trim();
//			isSearching = true;
			TableLayout productsTable = (TableLayout) findViewById(R.id.search_result_dlg);
			int count = productsTable.getChildCount();
			TableRow row;
			String productCode;
			for (int i = 1; i < count; i++) {
				row = (TableRow) productsTable.getChildAt(i);
//				productCode = "";
//				productCode = ((TextView) row.getChildAt(0)).getText()
//						.toString();

//				if (!productCode.toLowerCase().contains(filterValue)
//						&& !filterValue.equals(""))
//					row.setVisibility(TableRow.GONE);
//				else
					row.setVisibility(TableRow.VISIBLE);
			}

			productsTable.refreshDrawableState();
			productsTable.invalidate();

		} catch (Exception e) {
			logger.logException("filterproduction Exception", e);
		} finally {
			isSearching = false;
		}
	}
	
	
	/**
	 * Build Product Table
	 */
	private void buildProductTable() {
		try {
			TableLayout table = (TableLayout) findViewById(R.id.search_result_dlg);
			int textColor = getResources().getColor(
					R.color.table_item_text_color);
			int tableItemBg = getResources().getColor(R.color.table_item_bg);

			for (ProductBean productBean : productBeans) {
				TableRow productsRow = new TableRow(this);
				productsRow.setTag(productBean);

				LayoutParams layoutParams = new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

				productsRow.setLayoutParams(layoutParams);
				productsRow.setBackgroundColor(getResources().getColor(
						R.color.table_border_color));

				LayoutParams otherParams = new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

				otherParams.setMargins(1, 0, 0, 1);

				TextView txtProductDescription = new TextView(this);
				txtProductDescription.setTextAppearance(this,
						R.style.table_item_font);
				txtProductDescription.setText(productBean.getDescription());
				txtProductDescription.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtProductDescription.setPadding(5, 2, 5, 2);
				txtProductDescription.setBackgroundColor(tableItemBg);
				txtProductDescription.setTextSize(18);
				txtProductDescription.setTextColor(textColor);
				productsRow.addView(txtProductDescription, otherParams);

				TextView txtMsisdn = new TextView(this);
				txtMsisdn.setTextAppearance(this, R.style.table_item_font);
				txtMsisdn.setText(productBean.getUnitPrice());
				txtMsisdn.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtMsisdn.setPadding(5, 2, 2, 0);
				txtMsisdn.setBackgroundColor(tableItemBg);
				// txtMsisdn.setTextSize(textSize);
				txtMsisdn.setTextColor(textColor);
				productsRow.addView(txtMsisdn, otherParams);

				EditText txtQuantity = new EditText(this);
				txtQuantity.setTextAppearance(this, R.style.table_item_font);
				txtQuantity.setText("");
				txtQuantity.setGravity(Gravity.CENTER_HORIZONTAL
						| Gravity.CENTER_VERTICAL);
				txtQuantity.setPadding(5, 2, 5, 2);
				txtQuantity
						.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
								4) });
				txtQuantity.setTextColor(textColor);
				txtQuantity.setInputType(InputType.TYPE_CLASS_NUMBER);
				txtQuantity.setBackgroundColor(tableItemBg);
				productsRow.addView(txtQuantity, otherParams);

				table.addView(productsRow);
				productsRow.invalidate();
			}
		} catch (Exception e) {
			logger.logException("buildProductTable Exception ", e);
		}
	}

	@Override
	public void onClick(View view) {
		try {

			switch (view.getId()) {
			case R.id.add_search_items:
				addSearchItems();
				break;
			case R.id.cancel_result:
				this.finish();
				break;
			case R.id.search_product:
				this.filterproducts();
				break;
			case R.id.clear_product:
				this.searchFilter.setText("");
				this.filterClearProducts();
				break;
				
			default:
				break;
			}
		} catch (Exception e) {
			logger.logException("onClick Exception ", e);
		}

	}

	private void addSearchItems() {
		try {

			TableLayout productsTable = (TableLayout) findViewById(R.id.search_result_dlg);
			int count = productsTable.getChildCount();
			TableRow row;
			String quantity;

			ProductBean productBean;

			List<ProductBean> productBeanList = new ArrayList<ProductBean>();
			List<String> productBeanQuantityList = new ArrayList<String>();

			for (int i = 1; i < count; i++) {
				row = (TableRow) productsTable.getChildAt(i);
				quantity = ((EditText) row.getChildAt(2)).getText().toString()
						.trim();
				if (!quantity.equals("")) {
					productBean = (ProductBean) row.getTag();
					productBeanList.add(productBean);
					productBeanQuantityList.add(quantity);

				}
			}

			roverApp.getViewContext().put(
					RoverConstants.CURRENT_ORDER_PRODUCT_LIST, productBeanList);
			roverApp.getViewContext().put(
					RoverConstants.CURRENT_ORDER_QUANTITY_LIST,
					productBeanQuantityList);
			setResult(RoverConstants.CURRENT_ORDER_SUCESS);
			this.finish();
		} catch (Exception e) {
			logger.logException("addSearch Items", e);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.product_selection, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.add_search_items:
			addSearchItems();
			return true;

		case R.id.cancel_result:
			connfirmCancel();
			return true;

		case R.id.calculate_price:
			calculatePrice();
			return true;

		default:
			return super.onOptionsItemSelected(item);

		}
	}

	/**
	 * Calculate Price
	 */
	private void calculatePrice() {
		try {
			TableLayout tableLayout = (TableLayout) findViewById(R.id.search_result_dlg);

			TableRow row;
			double totalPrice = 0.0, price = 0.0;
			EditText quantityText;
			int count = tableLayout.getChildCount();
			String quantity;
			for (int i = 1; i < count; i++) {
				row = (TableRow) tableLayout.getChildAt(i);

				quantityText = (EditText) row.getChildAt(2);
				quantity = quantityText.getText().toString().trim();
				if (!quantity.equals("")) {
					price = Double.parseDouble(((TextView) row.getChildAt(1))
							.getText().toString());

					totalPrice += price * Integer.parseInt(quantity);
				}
			}

//			((TextView) findViewById(R.id.total_price)).setText(String
//					.valueOf(Math.round(totalPrice)));

			roverApp.showMessage("Total Amount :" + Math.round(totalPrice),
					Toast.LENGTH_LONG);

		} catch (Exception e) {
			logger.logException("Calculate Price", e);
		}

	}

	private void connfirmCancel() {
		try {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					getResources().getString(R.string.confirm_cancel))
					.setCancelable(false)
					.setPositiveButton(
							getResources().getString(R.string.common_yes),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
									SearchProductActivity.this.finish();
								}
							})
					.setNegativeButton(
							getResources().getString(R.string.common_no),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});
			builder.show();

		} catch (Exception e) {
			logger.logException("confirmCancel Exception", e);
		}

	}
}